package com.xmcowell.sportpacemaster.utils;

import android.content.Context;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;

import com.xmcowell.sportpacemaster.R;
import com.xmcowell.sportpacemaster.base.BaseModel;
import com.xmcowell.sportpacemaster.config.Contents;
import com.xmcowell.sportpacemaster.layout.entity.DaoSession;
import com.xmcowell.sportpacemaster.layout.entity.TrainTimesTable;
import com.xmcowell.sportpacemaster.layout.entity.TrainTimesTableDao;
import com.xmcowell.sportpacemaster.layout.entity.UserInfo;
import com.xmcowell.sportpacemaster.utils.retrofit.APIFactory;
import com.xmcowell.sportpacemaster.utils.retrofit.HttpResult;

import java.sql.Time;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 上传数据工具类
 * Created by fanyingmao on 16/10/26.
 */
public class TrainUitls {
    Context mContext;
    DaoSession mDaoSession;

    private int age;
    private UserInfo mUserInfo;
    int lastDay;

    public TrainUitls(Context mContext) {
        this.mContext = mContext;

        mDaoSession = DaoManager.getInstance().getDaoSession();
//        mUserInfo = DaoManager.getInstance().getUserInfo();
    }

    public void upData(APIFactory retrofitUtil) {
        if (PreferencesUtils.getBooleanFromSPMap(mContext, Contents.IS_LOGIN)) {
            mUserInfo = DaoManager.getInstance().getUserInfo();
        } else {
            mUserInfo = null;
        }

        if (mUserInfo != null) {//如果用户信息不存在，不上传数据
            String userId = mUserInfo.getId();
            String deviceId = Settings.System.getString(mContext.getContentResolver(), Settings.System.ANDROID_ID);
            Contents.IMEI = deviceId;
            Log.e("TrainUitls","上传数据使用的deviceId = "+deviceId);
            List<HashMap<String, Object>> listMap = new ArrayList<>();
            List<TrainTimesTable> list = mDaoSession.getTrainTimesTableDao().queryBuilder()
                    .where(TrainTimesTableDao.Properties.IsUpdate.eq(false),
                            TrainTimesTableDao.Properties.UserId.eq(userId)).list();
            if (list.size() == 0)
                return;
            for (int i = 0; i < list.size(); i++) {
                HashMap<String, Object> param = new HashMap<>();
                param.put("clientId", userId);
                param.put("sporttype", list.get(i).getSporttype());
                param.put("courseId", list.get(i).getCourseId());
                param.put("movementId", list.get(i).getMovementId());
                param.put("deviceId", deviceId);
                param.put("terminalId", Contents.IMEI);
                Log.e("startTime", "上传数据，本次运动的开始时间：" + TimeUtil.ConverToString2(list.get(i).getStartTime()));
                Log.e("startTime", "上传数据，本次运动的结束时间：" + TimeUtil.ConverToString2(list.get(i).getEndTime()));
                param.put("startTime", TimeUtil.ConverToString2(list.get(i).getStartTime()));
                param.put("finishTIme", TimeUtil.ConverToString2(list.get(i).getEndTime()));
                param.put("kcal", list.get(i).getKcal());
                param.put("distance", list.get(i).getDistance());
                param.put("count", list.get(i).getCount());
                param.put("deviceWeight", list.get(i).getDeviceWeight());
                param.put("weight", list.get(i).getWeight());
                param.put("height", list.get(i).getHeight());
                param.put("bmi", list.get(i).getBmi());
                if (list.get(i).getCourseFinish() == null) {
                    param.put("courseFinish", 0);
                } else {
                    param.put("courseFinish", 1);
                }
//                param.put("courseFinish", list.get(i).getCourseFinish() ? 1 : 0);
                param.put("courseBn", list.get(i).getCourseBn());
//            param.put("movementSeq", list.get(i).getCourseBn());
                param.put("synckey", list.get(i).getSynckey());
                param.put("movementSeq", list.get(i).getMovementSeq());
                listMap.add(param);
            }
            String json = new Gson().toJson(listMap);
            HashMap<String, Object> map = new HashMap<>();
            map.put("jsonlist", json);
            Log.e("TrainUtils", "上传的参数：" + json);
            Call<HttpResult<List<String>>> call = retrofitUtil.getService().sportUpDate(BaseModel.getParam("sportDataSyncController_sportDataSync", map));
            call.enqueue(new Callback<HttpResult<List<String>>>() {
                @Override
                public void onResponse(Call<HttpResult<List<String>>> call, Response<HttpResult<List<String>>> response) {
                    if (response.body().isSuccess()) {
                        List<String> list = response.body().getDatasource();
                        for (int i = 0; i < list.size(); i++) {
                            List<TrainTimesTable> listTrainTimesTable = mDaoSession.getTrainTimesTableDao().queryBuilder().where(TrainTimesTableDao.Properties.Synckey.eq(list.get(i))).list();
                            if (listTrainTimesTable.size() > 0) {
                                listTrainTimesTable.get(0).setIsUpdate(true);
                                mDaoSession.getTrainTimesTableDao().save(listTrainTimesTable.get(0));
                            }
                        }
                        ToastUtil.show(mContext, R.string.data_synchronization_is_successful);
                    } else {
                        if (response.body().getMessage().equals("API系统接口异常错误,请联系系统管理员!")) {
                            ToastUtil.show(mContext, response.body().getResultType());
                        }

                    }
                }

                @Override
                public void onFailure(Call<HttpResult<List<String>>> call, Throwable t) {
                    ToastUtil.show(mContext, R.string.data_synchronization_is_failure);
                }
            });
        }
    }

    /**
     * 自由运动
     *
     * @param distance  距离，单位 m
     * @param kcal      卡路里
     * @param type      运动类型
     * @param mac       设备id
     * @param startDate 运动时间
     */
    public void saveIMData(String userid, Long distance, Long kcal, int type, String mac, Date startDate) {
//        String deviceId = PreferencesUtils.getValueFromSPMap(mContext,Contents.QR_DEVICE_ID);
        TrainTimesTable mTrainTimesTable = new TrainTimesTable();
        mTrainTimesTable.setUserId(userid);
        mTrainTimesTable.setDistance(distance);
        mTrainTimesTable.setKcal(kcal);
        mTrainTimesTable.setDeviceId(mac);
        mTrainTimesTable.setType(type);
        mTrainTimesTable.setSporttype(1);
        mTrainTimesTable.setIsUpdate(false);
        mTrainTimesTable.setStartTime(startDate);
        mTrainTimesTable.setEndTime(new Date());
        mTrainTimesTable.setSynckey(UUID.randomUUID().toString());
        mDaoSession.getTrainTimesTableDao().save(mTrainTimesTable);
    }

    /**
     * 获取距离
     *
     * @param mContext
     * @param distance 米
     * @return km、mi 千米或英里
     */

    public static double getDistance(Context mContext, long distance) {
        boolean unit = PreferencesUtils.getBooleanFromSPMap(mContext, Contents.UNITS);
        if (unit) {
            return distance / 1000f;
        } else {
            return distance * 0.6213712 / 1000f;
        }
    }

    public static String dbToStr(double d) {
        int pace = Integer.valueOf((int) Math.round(d));
        if (pace <= 0) {
            return "00:00";
        } else {
            return TimeUtil.secToTime2(pace);
        }
    }

    public static double getKcal(Context context,float speed, int splod, float weith) {
        if (PreferencesUtils.getBooleanFromSPMap(context, Contents.UNITS)) {
            return getPKcal(speed, splod, weith);
        } else {
            return getEKcal(speed, splod, weith);
        }
    }

    public static double getPKcal(float speed, int splod, float weith) {
        double res = 0;
        if (speed <= 5.92) {
            res = (1 + (0.4721 * speed) + (0.085128 * speed * splod)) * weith;
        } else {
            res = (1 + (0.95194 * speed) + (0.042564 * speed * splod)) * weith;
        }
        return res / 3600;
    }

    public static double getEKcal(float speed, int splod, float weith) {
        double res = 0;
        if (speed <= 3.7) {
            res = (1 + (0.768 * speed) + (0.137 * speed * splod)) * weith / 2.2;
        } else {
            res = (1 + (1.532 * speed) + (0.685 * speed * splod)) * weith / 2.2;
        }
        return res / 3600;
    }

}
